package utils

import config.JwtConfig
import pdi.jwt._
import shared.pojo.Pojo.UserInfo

import java.time.Clock
import scala.concurrent.duration._
import upickle.default._

/**
 * Created by yz on 9/8/2022
 */
object JwtUtils {

  def createToken(config: JwtConfig, userInfo: UserInfo)(implicit clock: Clock) = {
    val json = write(userInfo)
    val claim = JwtClaim(json).issuedNow.expiresIn(30.days.toSeconds)
    val token = Jwt.encode(claim, config.secret, JwtAlgorithm.HS384)
    token
  }

  def decodeToken(config: JwtConfig, token: String)(implicit clock: Clock) = {
    Jwt.decode(token, config.secret, Seq(JwtAlgorithm.HS384)).filter { x =>
      x.isValid
    }.map(_.content).map { decodedClaim =>
      read[UserInfo](decodedClaim)
    }
  }


}
